package com.hjr.leetcode.question100;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

/**
 *17. 电话号码的字母组合
 * 给定一个仅包含数字 2-9 的字符串，返回所有它能表示的字母组合。答案可以按 任意顺序 返回。
 *
 * 给出数字到字母的映射如下（与电话按键相同）。注意 1 不对应任何字母。
 */
public class q17 {

    public static void main(String[] args) {
        System.out.println(letterCombinations("23"));
    }

    //回溯解法 ！！！ 1ms 41mb
    public static List<String> letterCombinations(String digits) {
        List<String> result = new ArrayList<String>();
        if (digits.isEmpty()) {
            return result;
        }

        HashMap<Character, Character[]> map = new HashMap<>() {{
            put('2', new Character[]{'a', 'b', 'c'});
            put('3', new Character[]{'d', 'e', 'f'});
            put('4', new Character[]{'g', 'h', 'i'});
            put('5', new Character[]{'j', 'k', 'l'});
            put('6', new Character[]{'m', 'n', 'o'});
            put('7', new Character[]{'p', 'q', 'r', 's'});
            put('8', new Character[]{'t', 'u', 'v'});
            put('9', new Character[]{'w', 'x', 'y', 'z'});
        }};

        backtrack(result, map, digits, 0, new StringBuffer());

        return result;
    }

    private static void backtrack(List<String> result, HashMap<Character, Character[]> map, String digits, int index, StringBuffer stringBuffer) {
        if (index == digits.length()) {
            result.add(stringBuffer.toString());
        } else {
            Character[] characters = map.get(digits.charAt(index));
            for (Character character : characters) {
                stringBuffer.append(character);
                backtrack(result, map, digits, index + 1, stringBuffer);
                stringBuffer.deleteCharAt(stringBuffer.length() - 1);
            }
        }
    }
}
